﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using RubricaSentimentale.Model;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Shell;

namespace RubricaSentimentale.View
{
    public partial class AggiungiPersona : PhoneApplicationPage
    {
        Persona p=new Persona("","");
        ViewModel vm;
        private bool enableTextChange = false;

         PhotoChooserTask pct = new PhotoChooserTask();

        private bool _saved;
        /// <summary>
        /// Property that indicate the save state of the information
        /// </summary>
        public bool Saved {
            get { return Saved; }
            set {
                (ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = !value;
                _saved = value;
            }
        }



        public AggiungiPersona()
        {
            InitializeComponent();
            pct.Completed += new EventHandler<PhotoResult>(pct_Completed);

            vm = (ViewModel)Utility.LoadState("ViewModel");
            //If the user choose to modify contact enter the edit mode
            this.tbxNome.TextChanged += new TextChangedEventHandler(TextChanged);
            this.tbxCognome.TextChanged += new TextChangedEventHandler(TextChanged);
            if (vm.contesto == ViewModel.Context.Edit)
            {
                this.tbxTitle.Text="Modifica";
                
            }
            this.Loaded += new RoutedEventHandler(AggiungiPersona_Loaded);
            
            this.DataContext = p;
        }

        void AggiungiPersona_Loaded(object sender, RoutedEventArgs e)
        {
            if (vm.contesto == ViewModel.Context.Edit)
            {
                Saved = true;
                this.p = vm.Current;
                this.DataContext = p;
            }
        }

        void TextChanged(object sender, TextChangedEventArgs e)
        {
            
                Saved = false;
        }


        /// <summary>
        /// Function to handle the save button tap
        /// </summary>
        private void BtnSave_Tap(object sender, System.EventArgs e)
        {
            save();
        }

        /// <summary>
        /// Function to handle the image button tap
        /// </summary>
        private void BtnImage_Tap(object sender, GestureEventArgs e)
        {
            pct.Show();
        }

        /// <summary>
        /// Function that is invoked when the user have choosen the photo
        /// </summary>
        void pct_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                
                BitmapImage bi = new BitmapImage();
                bi.SetSource(e.ChosenPhoto);
                WriteableBitmap wb = new WriteableBitmap(bi);
                Random r=new Random((int)DateTime.Now.Ticks);
                string filename="Img_"+r.Next(99999999)+".jpg";
                IsolatedStorageFileStream str= IsolatedStorageFile.GetUserStoreForApplication().CreateFile(filename);
                wb.SaveJpeg(str,200,200,0,100);
                str.Close();
                p.ImgSrc = filename;
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = false;
            if (!_saved && p.Nome!="" &&p.Cognome!="")
            {
                var r=MessageBox.Show("Vuoi salvare le modifiche al contatto?","Salva",MessageBoxButton.OKCancel);
                if (r == MessageBoxResult.OK)
                {
                    save();
                }

            } 
            base.OnBackKeyPress(e);
        }

        private void save()
        {
            if (tbxNome.Text == "")
                MessageBox.Show("Inserisci il nome del contatto");
            else if (tbxCognome.Text == "")
                MessageBox.Show("Inserisci il cognome del contatto");
            else
            {
                
                vm.agenda.AddPersona(p);
                Utility.SaveState("ViewModel", vm);
                Utility.Save(vm, typeof(ViewModel));
                Saved = true;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            vm.Current = p;
            NavigationService.Navigate(new Uri("/View/AggiungiDettagli.xaml", UriKind.Relative));
        }

        private void btnadd_Click(object sender, System.EventArgs e)
        {
        	Button_Click(sender,null);
        }

    }
}